package cn.openea.perpartner.componet.web.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.openea.perpartner.componet.web.entity.Attachment;
import cn.openea.perpartner.componet.web.entity.dto.AttachDto;
import cn.openea.perpartner.componet.web.mapper.AttachmentMapper;
import cn.openea.perpartner.componet.web.service.IAttachmentService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * (Attachment)表服务实现类
 *
 * @author Weird077
 * @since 2023-02-03 12:17:57
 */
@Service
public class AttachmentServiceImpl extends ServiceImpl<AttachmentMapper, Attachment> implements IAttachmentService {

    private static final String IMAGES_TYPE = "png,jpg,jpeg,gif,bmp,webp,psd,svg,ico,tiff";
    @Value("${tencent.cos.bucket}")
    private String bucket;
    @Value("${tencent.cos.region}")
    private String region;

    @Override
    public boolean add(Attachment attachment) {
        String suffix = attachment.getSuffix().toLowerCase();
        attachment.setBucket(bucket);
        attachment.setRegion(region);
        attachment.setStatus("1");
        attachment.setType(IMAGES_TYPE.contains(suffix) ? "0" : "1");
        return save(attachment);
    }

    @Override
    public List<Attachment> selectList(AttachDto dto) {
        LambdaQueryWrapper<Attachment> wrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(dto.getUserId())) {
            wrapper.eq(Attachment::getUserId, dto.getUserId());
        }
        if (StrUtil.isNotBlank(dto.getType())) {
            wrapper.eq(Attachment::getType, dto.getType());
        }
        if (StrUtil.isNotBlank(dto.getStatus())) {
            wrapper.eq(Attachment::getStatus, dto.getStatus());
        }
        if (StrUtil.isNotBlank(dto.getSearchStr())) {
            wrapper.and(wrap -> wrap.like(Attachment::getFileName, dto.getSearchStr())
                    .or().like(Attachment::getNickName, dto.getSearchStr())
                    .or().like(Attachment::getNewFileName, dto.getSearchStr())
            );
        }
        wrapper.orderByDesc(Attachment::getCreateTime);
        wrapper.orderByDesc(Attachment::getSort);
        return list(wrapper);
    }
}

